//
//  DynamicColumnFieldCore.m
//  
//
//  Created by wjxfhxy on 15/12/30.
//
//

#import "DynamicColumnFieldCore.h"
#import "DynamicColumnFieldCore+Internal.h"
#import "DynamicColumnFieldCore+ChoicePhoto.h"
#import "ReviewCurrentPositionViewController.h"
#import "DynamicColumnFieldCore+DropDownData.h"

@interface DynamicColumnFieldCore (PrivateDelegate)<ExpandDynamicCellDelegate,XUIPickerPanelViewDataSource,XUIPickerPanelViewDelegate,XMSSimpleDownloadManagerDelegate,XMSDataOperationManagerDelegate>

@end

@implementation DynamicColumnFieldCore

-(id)init
{
    self = [super init];
    
    return self;
}

-(void)loadView
{
    _manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
    
    if([_dataSource respondsToSelector:@selector(headImageCacheFolderOfDynamicColumnFieldCore:)])
        _headImageCacheFolder = [[_dataSource headImageCacheFolderOfDynamicColumnFieldCore:self] copy];
    
    if([_dataSource respondsToSelector:@selector(headImagePathOfDynamicColumnFieldCore:)])
        _headImagePath = [[_dataSource headImagePathOfDynamicColumnFieldCore:self] copy];
    
    UIView *superView = [_delegate superViewOfDynamicColumnFieldCore:self];
    CGRect frame = superView.bounds;
    if([_delegate respondsToSelector:@selector(frameOfDynamicColumnFieldCore:)])
        frame = [_delegate frameOfDynamicColumnFieldCore:self];
    
    _gtable = [[XUIGroupTableView alloc]initWithFrame:frame];
    _gtable.backgroundColor = [[UITableView appearance] backgroundColor];
    _gtable.delegate = self;
    _gtable.dataSource = self;
    [superView addSubview:_gtable];
}

-(void)unloadView
{
    [_sdm terminateAllDownloadTask];
    
    [_manager terminateRequest];
    
    if(_headImageCacheFolder.length > 0)
        [XLGHeadImageDownloadQueue clearTag:@"11223344" forKey:_headImageCacheFolder];
}

- (XUIGroupTableView*)getGrouptableView
{
    return  _gtable;
}

#pragma mark --
#pragma mark -- group table view delegate

- (NSUInteger)numberOfGroupsInGroupTableView:(XUIGroupTableView *)groupTableView
{
    XMSQueueDictionary *constraint = [_dataSource constraintOfDynamicColumnFieldCore:self];
    
    return constraint.count;
}

-(NSUInteger)groupTableView:(XUIGroupTableView *)groupTableView numberOfRowsInGroup:(NSInteger)group
{
    XMSQueueDictionary *constraint = [_dataSource constraintOfDynamicColumnFieldCore:self];
    
    return ((NSArray*)[constraint getValueForIndex:group]).count;
}

- (UIView *)groupTableView:(XUIGroupTableView *)groupTableView viewForHeaderInGroup:(NSInteger)group
{
    UIView *view = nil;
    if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:groupTitleInGroup:)])
    {
        CGFloat height = [self groupTableView:groupTableView heightForHeaderInGroup:group];
        
        id groupTitle = [_delegate dynamicColumnFieldCore:self groupTitleInGroup:group];
        if([groupTitle isKindOfClass:[NSString class]] && [groupTitle length] > 0)
        {
            view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, groupTableView.width, height)];
            view.backgroundColor = [UIColor clearColor];
            UILabel *l = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 150, height)];
            l.backgroundColor = [UIColor clearColor];
            l.font = [UIFont systemFontOfSize:14];
            l.textColor = [UIColor grayColor];
            l.text = groupTitle;
            [view addSubview:l];
        }
        else if([groupTitle isKindOfClass:[NSAttributedString class]] && [groupTitle length] > 0)
        {
            view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, groupTableView.width, height)];
            view.backgroundColor = [UIColor clearColor];
            UILabel *l = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 150, height)];
            l.backgroundColor = [UIColor clearColor];
            l.font = [UIFont systemFontOfSize:14];
            l.textColor = [UIColor grayColor];
            l.attributedText = groupTitle;
            [view addSubview:l];
        }
    }
    
    return view;
}

-(CGFloat)groupTableView:(XUIGroupTableView *)groupTableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    XMSQueueDictionary *constraint = [_dataSource constraintOfDynamicColumnFieldCore:self];
    
    FieldDescript *fieldDescript = [constraint valueAtKeyArrayIndex:indexPath.section valueArrayIndex:indexPath.row];
    
    if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:dynamicColumnCellWillCaleHeight:)])
    {
        CGFloat height = [_delegate dynamicColumnFieldCore:self dynamicColumnCellWillCaleHeight:fieldDescript];
        if(height != 0)
            return height;
    }
    
    if(fieldDescript.controlType.intValue == DynamicFieldControlTypeStaticText)
    {
        id value = [self valueForFieldDescript:fieldDescript];
        value = [self formatValue:value fieldDescript:fieldDescript];
        return [ExpandDynamicCellFactory caleStaticText:fieldDescript.controlType.intValue heightWithText:value forContainWidth:_gtable.width];
    }
    
    return [ExpandDynamicCellFactory caleHeght:fieldDescript];
}

-(CGFloat)groupTableView:(XUIGroupTableView *)groupTableView heightForHeaderInGroup:(NSInteger)group
{
    if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:heightForHeaderInGroup:)])
        return [_delegate dynamicColumnFieldCore:self heightForHeaderInGroup:group];
    return 26;
}

-(XUIGroupTableViewCell*)groupTableView:(XUIGroupTableView *)groupTableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    XMSQueueDictionary *constraint = [_dataSource constraintOfDynamicColumnFieldCore:self];
    
    FieldDescript *fieldDescript = [constraint valueAtKeyArrayIndex:indexPath.section valueArrayIndex:indexPath.row];
    
    ExpandDynamicCell *cell = nil;
    
    if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:dynamicColumnCellWillCreate:)])
    {
        cell = [_delegate dynamicColumnFieldCore:self dynamicColumnCellWillCreate:fieldDescript];
        if(cell != nil)
            return cell;
    }
    
    cell = [ExpandDynamicCellFactory factory:fieldDescript];
    cell.delegate = self;
    
    DynamicColumnFieldViewType vclType = [_dataSource typeOfDynamicColumnFieldCore:self];
    
    if(vclType == DynamicColumnFieldViewTypeModify || vclType == DynamicColumnFieldViewTypeReview)
    {
        id value = [self valueForFieldDescript:fieldDescript];
        
        if([cell isMemberOfClass:[TextInputGroupTableViewCell class]] ||
           [cell isMemberOfClass:[DateGroupTableViewCell class]] ||
           [cell isMemberOfClass:[DropDownGroupTableViewCell class]] ||
           [cell isMemberOfClass:[SimilarTextInputGroupTableViewCell class]] ||
           [cell isMemberOfClass:[DecimalGroupTableViewCell class]] ||
           [cell isMemberOfClass:[StaticTextGroupTableViewCell class]] ||
           [cell isMemberOfClass:[DateTimeStaticTextGroupTableViewCell class]] ||
           [cell isMemberOfClass:[MultiSelectStaticTextGroupTableViewCell class]] ||
           
           [cell isMemberOfClass:[DropDownTextGroupTableViewCell class]])
        {
            ((TextInputGroupTableViewCell*)cell).text = [self formatValue:value fieldDescript:fieldDescript];
        }
        else if([cell isMemberOfClass:[MultiSelectGroupTableViewCell class]])
        {
            if(value!= nil && [value isKindOfClass:[NSNull class]] == NO)
            {
                NSString *text = value;
                ((MultiSelectGroupTableViewCell*)cell).selectitems = text.length > 0 ? [text componentsSeparatedByString:SplitCommaString] : nil;
                ((MultiSelectGroupTableViewCell*)cell).text = [self formatValue:text fieldDescript:fieldDescript];
            }
        }
        else if([cell isMemberOfClass:[TextAreaGroupTableViewCell class]])
        {
            if(value!= nil && [value isKindOfClass:[NSNull class]] == NO)
            {
                ((TextAreaGroupTableViewCell*)cell).text = [NSString stringValue:value];
            }
        }
        else if([cell isMemberOfClass:[PositionGroupTableViewCell class]])
        {
            if(value!= nil && [value isKindOfClass:[NSNull class]] == NO)
            {
                ((PositionGroupTableViewCell*)cell).selectAddress = value;
                ((TextInputGroupTableViewCell*)cell).text = [self formatValue:value fieldDescript:fieldDescript];
            }
        }
        else if([cell isMemberOfClass:[PositionStaticTextGroupTableViewCell class]])
        {
            ((PositionStaticTextGroupTableViewCell*)cell).text = [self formatValue:value fieldDescript:fieldDescript];;
        }
        else if ([cell isMemberOfClass:[HeadImageGroupTableViewCell class]])
        {
            _headImagePath = [self formatValue:value fieldDescript:fieldDescript];
            if(_headImagePath.length > 0)
            {
                [XLGHeadImageDownloadQueue setOrStartDownloadHeadImageWhenAddHeadImageURL:[XLGContext fileDownloadURL:_headImagePath] inImageView:((HeadImageGroupTableViewCell*)cell).headImageView tag:@"11223344" forKey:_headImageCacheFolder];
            }
        }
        else if([cell isMemberOfClass:[ImagePanelStaticGroupTableViewCell class]])
        {
            ImagePanelStaticGroupTableViewCell *c = (ImagePanelStaticGroupTableViewCell *)cell;
            c.imageNames = value;
            DispatchThread(^
                           {
                               NSString *tmpPath = [[XMSFileHelper tempPath] stringByAppendingPathComponent:ImagePanelThumbDowdloadFolder];
                               if([XMSFileHelper isDirExist:tmpPath] != YES)
                                   [XMSFileHelper createDir:tmpPath];
                               NSArray *imageNames = value;
                               for(NSString *imageName in imageNames)
                               {
                                   NSString *imagePath = [tmpPath stringByAppendingPathComponent:imageName];
                                   
                                   if([XMSFileHelper isFileExist:imagePath] == YES)
                                   {
                                       UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
                                       DispatchMainThreadAsync(^
                                                               {
                                                                   [c addImage:image withTag:imagePath];
                                                               });
                                   }
                                   else
                                   {
                                       UIImage *image = [UIImage imageNamed:@"img_defautlimage.png"];
                                       DispatchMainThreadAsync(^
                                                               {
                                                                   [c addImage:image withTag:imagePath];
                                                               });
                                       if(_sdm == nil)
                                       {
                                           _sdm = [[XMSSimpleDownloadManager alloc] initWithDelegate:self];
                                       }
                                       [_sdm downloadThumbImageFile:imageName withStorePath:imagePath attachment:c];
                                   }
                               }
                           });
            
        }
        else if([cell isMemberOfClass:[ImagePanelGroupTableViewCell class]])
        {
            ImagePanelGroupTableViewCell *c = (ImagePanelGroupTableViewCell *)cell;
            DispatchThread(^
                           {
                               NSString *tmpPath = [[XMSFileHelper tempPath] stringByAppendingPathComponent:ImagePanelThumbDowdloadFolder];
                               if([XMSFileHelper isDirExist:tmpPath] != YES)
                                   [XMSFileHelper createDir:tmpPath];
                               NSArray *imageNames = value;
                               for(NSString *imageName in imageNames)
                               {
                                   NSString *imagePath = [tmpPath stringByAppendingPathComponent:imageName];
                                   
                                   if([XMSFileHelper isFileExist:imagePath] == YES)
                                   {
                                       UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
                                       DispatchMainThreadAsync(^
                                                               {
                                                                   [c addImage:image withTag:imagePath];
                                                               });
                                   }
                                   else
                                   {
                                       UIImage *image = [UIImage imageNamed:@"img_defautlimage.png"];
                                       DispatchMainThreadAsync(^
                                                               {
                                                                   [c addImage:image withTag:imagePath];
                                                               });
                                       if(_sdm == nil)
                                       {
                                           _sdm = [[XMSSimpleDownloadManager alloc] initWithDelegate:self];
                                       }
                                       [_sdm downloadThumbImageFile:imageName withStorePath:imagePath attachment:c];
                                   }
                               }
                           });
        }
        else if([cell isMemberOfClass:[MixedPanelGroupTableViewCell class]])
        {
            MixedPanelGroupTableViewCell *c = (MixedPanelGroupTableViewCell *)cell;
            DispatchThread(^
                           {
                               NSString *tmpPath = [[XMSFileHelper tempPath] stringByAppendingPathComponent:ImagePanelThumbDowdloadFolder];
                               if([XMSFileHelper isDirExist:tmpPath] != YES)
                                   [XMSFileHelper createDir:tmpPath];
                               NSArray *imageNames = value;
                               for(WorkflowAttachmentInfo *attach in imageNames)
                               {
                                   NSString *imageName = [NSString stringWithFormat:@"%@",[attach.fielFullName lastPathComponent]];
                                   NSString *imagePath = [tmpPath stringByAppendingPathComponent:imageName];
                                   
                                   if([XMSFileHelper isFileExist:imagePath] == YES)
                                   {
                                       UIImage *image;
                                       if([[imageName pathExtension] isEqualToString:@"wav"])
                                       {
                                           image = [UIImage imageNamed:@"input_function_voice"];
                                       }
                                       else if([[imageName pathExtension] isEqualToString:@"mov"])
                                       {
                                           image = [UIImage imageNamed:@"input_function_record"];
                                       }
                                       else
                                       {
                                           image = [UIImage imageWithContentsOfFile:imagePath];
                                       }
                                       DispatchMainThreadAsync(^
                                                               {
                                                                   [c addImage:image withTag:imagePath];
                                                               });
                                   }
                                   else
                                   {
                                       UIImage *image;
                                       if([[imageName pathExtension] isEqualToString:@"wav"])
                                       {
                                           image = [UIImage imageNamed:@"input_function_voice"];
                                       }
                                       else if([[imageName pathExtension] isEqualToString:@"mov"])
                                       {
                                           image = [UIImage imageNamed:@"input_function_record"];
                                       }
                                       else
                                       {
                                           image = [UIImage imageNamed:@"img_defautlimage.png"];
                                       }
                                       DispatchMainThreadAsync(^
                                                               {
                                                                   [c addImage:image withTag:imagePath];
                                                               });
                                       if(_sdm == nil)
                                       {
                                           _sdm = [[XMSSimpleDownloadManager alloc] initWithDelegate:self];
                                       }
                                       [_sdm downloadThumbImageFile:attach.fielFullName withStorePath:imagePath attachment:c];
                                   }
                               }
                           });
        }
        else if([cell isMemberOfClass:[MixedPanelStaticGroupTableViewCell class]])
        {
            MixedPanelStaticGroupTableViewCell *c = (MixedPanelStaticGroupTableViewCell *)cell;
            DispatchThread(^
                           {
                               NSString *tmpPath = [[XMSFileHelper tempPath] stringByAppendingPathComponent:ImagePanelThumbDowdloadFolder];
                               if([XMSFileHelper isDirExist:tmpPath] != YES)
                                   [XMSFileHelper createDir:tmpPath];
                               NSArray *imageNames = value;
                               for(WorkflowAttachmentInfo *attach in imageNames)
                               {
                                   NSString *imageName = [NSString stringWithFormat:@"%@",[attach.fielFullName lastPathComponent]];
                                   NSString *imagePath = [tmpPath stringByAppendingPathComponent:imageName];
                                   
                                   if([XMSFileHelper isFileExist:imagePath] == YES)
                                   {
                                       UIImage *image;
                                       if([[imageName pathExtension] isEqualToString:@"wav"])
                                       {
                                           image = [UIImage imageNamed:@"input_function_voice"];
                                       }
                                       else if([[imageName pathExtension] isEqualToString:@"mov"])
                                       {
                                           image = [UIImage imageNamed:@"input_function_record"];
                                       }
                                       else
                                       {
                                           image = [UIImage imageWithContentsOfFile:imagePath];
                                       }
                                       DispatchMainThreadAsync(^
                                                               {
                                                                   [c addImage:image withTag:imagePath];
                                                               });
                                   }
                                   else
                                   {
                                       UIImage *image;
                                       if([[imageName pathExtension] isEqualToString:@"wav"])
                                       {
                                           image = [UIImage imageNamed:@"input_function_voice"];
                                       }
                                       else if([[imageName pathExtension] isEqualToString:@"mov"])
                                       {
                                           image = [UIImage imageNamed:@"input_function_record"];
                                       }
                                       else
                                       {
                                           image = [UIImage imageNamed:@"img_defautlimage.png"];
                                       }
                                       DispatchMainThreadAsync(^
                                                               {
                                                                   [c addImage:image withTag:imagePath];
                                                               });
                                       if(_sdm == nil)
                                       {
                                           _sdm = [[XMSSimpleDownloadManager alloc] initWithDelegate:self];
                                       }
                                       [_sdm downloadThumbImageFile:attach.fielFullName withStorePath:imagePath attachment:c];
                                   }
                               }
                           });
        }
        else if ([cell isMemberOfClass:[CreateUUIDGroupTableViewCell class]])
        {
            if([value isEqualToString:@""] == NO)
                ((CreateUUIDGroupTableViewCell *)cell).createdObj = value;
        }
        else if([cell isMemberOfClass:[CreateUserIdGroupTableViewCell class]])
        {
            ((CreateUserIdGroupTableViewCell *)cell).userId = value;
        }
        else if([cell isMemberOfClass:[CreateUserNameGroupTableViewCell class]])
        {
             ((CreateUserNameGroupTableViewCell *)cell).userName = value;
        }
        else if([cell isMemberOfClass:[CreateDeptIdGroupTableViewCell class]])
        {
            ((CreateDeptIdGroupTableViewCell *)cell).deptId = value;
        }
        else if([cell isMemberOfClass:[CreateDeptNameGroupTableViewCell class]])
        {
            ((CreateDeptNameGroupTableViewCell *)cell).deptName = value;
        }
        else if([cell isMemberOfClass:[CreateDateGroupTableViewCell class]])
        {
            ((CreateDateGroupTableViewCell *)cell).currentTime = value;
        }
    }
    
    if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:dynamicColumnCell:didCreate:)])
        [_delegate dynamicColumnFieldCore:self dynamicColumnCell:cell didCreate:fieldDescript];
    
    return cell;
}

- (void)groupTableView:(XUIGroupTableView *)XUIGroupTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [UIViewController closeKeyBoard];
    
    _selectedCell = (ExpandDynamicCell*)[XUIGroupTableView cellAtIndexPath:indexPath];
    
    XMSQueueDictionary *constraint = [_dataSource constraintOfDynamicColumnFieldCore:self];
    
    FieldDescript *fieldDescript = [constraint valueAtKeyArrayIndex:indexPath.section valueArrayIndex:indexPath.row];
    
    if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:handlerDynamicColumnCellDidSelected:)])
    {
        if([_delegate dynamicColumnFieldCore:self handlerDynamicColumnCellDidSelected:fieldDescript] == YES)
        {
            return;
        }
    }
    
    switch(fieldDescript.controlType.intValue)
    {
        case DynamicFieldControlTypeSingleSelect:
        case DynamicFieldControlTypeTextSingleSelect:
        {
            [self showPickerPanelViewController:fieldDescript.fieldLabel vclType:OtherPickPanelViewControllerTag];
            break;
        }
        case DynamicFieldControlTypeMultiSelect:
        {
            MultiSelectGroupTableViewCell *cell = (MultiSelectGroupTableViewCell*) _selectedCell;
            XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
            p.param[MultiSelectViewControllerPreSelectedItemsParamKey] = cell.selectitems.count > 0 ? cell.selectitems : @[];
            p.param[MultiSelectViewControllerTitleParamKey] = fieldDescript.fieldLabel;
            p.param[MultiSelectViewControllerSelectOptionsParamKey] = fieldDescript.optionals;
            [XUINavigationController pushViewControllerClass:[MultiSelectViewController class] withSwitchParam:p];
            break;
        }
        case DynamicFieldControlTypeDate:
        {
            [self showDatePickerPanelViewController:fieldDescript.fieldLabel vclType:DatePickPanelViewControllerTag];
            break;
        }
        case DynamicFieldControlTypeDateTime:
        {
            [self showDateTimePickerPanelViewController:fieldDescript.fieldLabel vclType:DateTimePickPanelViewControllerTag];
            break;
        }
        case DynamicFieldControlTypeHeadImage:
        {
            [self choicePhoto:1];
            break;
        }
        case DynamicFieldControlTypePositionStaticText:
        {
            NSString *address = [self valueForFieldDescript:fieldDescript];
            if(address.length >0 && [address isEqualToString:@";;"] == NO)
            {
                XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
                p.param[ReviewCurrentPositionViewControllerPositinAddressParamKey] = address;
                
                if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:willPushViewControllerParam:inFieldDescript:)])
                {
                    NSDictionary *dic = [_delegate dynamicColumnFieldCore:self willPushViewControllerParam:p.param inFieldDescript:fieldDescript];
                    if(dic != nil)
                        [p.param setDictionary:dic];
                }
                
                [XUINavigationController pushViewControllerClass:[ReviewCurrentPositionViewController class] withSwitchParam:p];
            }
        }
        case DynamicFieldControlTypeSwitchSelect:
        {
            if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:didSelectedSwitchSelectGroupTableCell:)])
                [_delegate dynamicColumnFieldCore:self didSelectedSwitchSelectGroupTableCell:fieldDescript];
            break;
        }
        case DynamicFieldControlTypeSingleSelectDic:
        case DynamicFieldControlTypeStaticSingleSelectDic:
        {
            [self showPickerPanelViewController:fieldDescript.fieldLabel vclType:DicPickPanelViewControllerTag];
        }
    }
}

-(NSIndexPath*)groupTableView:(XUIGroupTableView *)XUIGroupTableView findIndexPathWithTag:(NSString *)tag
{
    __block NSIndexPath *indexPath = nil;
    XMSQueueDictionary *constraint = [_dataSource constraintOfDynamicColumnFieldCore:self];
    [constraint enumerateObjectUsingBlockFromBegin:^(id key, id obj, NSUInteger idx1, NSUInteger idx2, BOOL *stop)
    {
        FieldDescript *fieldDescript = obj;
        if([fieldDescript.fieldName isEqualToString:tag])
        {
            indexPath = [NSIndexPath indexPathForRow:idx2 inSection:idx1];
            *stop = YES;
        }
    }];
    return indexPath;
}

-(void)groupTableViewWillBeginDragging:(XUIGroupTableView *)groupTableView
{
    if([_delegate respondsToSelector:@selector(groupTableViewWillBeginDragging:)])
        [_delegate groupTableViewWillBeginDragging:_gtable];
}

#pragma mark --
#pragma mark -- reload

- (void)reloadDyanmicField
{
    [_gtable reloadData];
    
    NSMutableArray *needLoadSingleSelect = [NSMutableArray new];
    
    XMSQueueDictionary *constraint = [_dataSource constraintOfDynamicColumnFieldCore:self];
    
    [constraint enumerateArrayValueUsingBlock:^(id key, id obj, NSUInteger idx, BOOL *stop)
    {
        FieldDescript *fieldDescript = obj;
        if(fieldDescript.controlType.intValue == DynamicFieldControlTypeSingleSelectDic ||
           fieldDescript.controlType.intValue == DynamicFieldControlTypeStaticSingleSelectDic ||
           fieldDescript.controlType.intValue == DynamicFieldControlTypeStaticText)
        {
            [needLoadSingleSelect addObject:fieldDescript];
        }
    }];
    
    if (needLoadSingleSelect.count > 0)
    {
        [self initSingleSelect:needLoadSingleSelect];
    }
}

#pragma mark --
#pragma mark -- pickerPanel delegate

- (void)showPickerPanelViewController:(NSString*)title vclType:(NSInteger)vclType
{
    XUIPickerPanelView *pick = [[XUIPickerPanelView alloc]initWithPickerPanelType:XUIPickerPanelViewTypeComBoBox];
    pick.vclType = vclType;
    pick.toolBarTitle = [NSString stringWithFormat:@"请选择%@",title];
    pick.delegate = self;
    pick.dataSource = self;
    [pick show];
}

- (void)showDatePickerPanelViewController:(NSString*)title vclType:(NSInteger)vclType
{
    XUIPickerPanelView *pick = [[XUIPickerPanelView alloc]initWithPickerPanelType:XUIPickerPanelViewTypeDate];
    pick.vclType = vclType;
    pick.toolBarTitle = [NSString stringWithFormat:@"请选择%@",title];
    pick.delegate = self;
    pick.dataSource = self;
    [pick show];
}

- (void)showDateTimePickerPanelViewController:(NSString*)title vclType:(NSInteger)vclType
{
    XUIPickerPanelView *pick = [[XUIPickerPanelView alloc]initWithPickerPanelType:XUIPickerPanelViewTypeDateTime];
    pick.vclType = vclType;
    pick.toolBarTitle = [NSString stringWithFormat:@"请选择%@",title];
    pick.delegate = self;
    pick.dataSource = self;
    [pick show];
}

- (NSInteger)defaultRowInPickerPanelViewController:(XUIPickerPanelView *)ppvcl
{
    switch(ppvcl.vclType)
    {
        case DicPickPanelViewControllerTag:
        {
            DicDropDownGroupTableViewCell *cell = (DicDropDownGroupTableViewCell*)_selectedCell;
            if(cell.dicData == nil)
                return 0;
            
            __block NSArray *i = [NSArray new];
            [_newSingleSelect enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
             {
                 if ([ppvcl.toolBarTitle rangeOfString:key].location != NSNotFound)
                 {
                     i = obj;
                 }
             }];
            return [i indexOfObject:cell.dicData] + 1;
            break;
        }
        case OtherPickPanelViewControllerTag:
        {
            XMSQueueDictionary *constraint = [_dataSource constraintOfDynamicColumnFieldCore:self];
            NSString *text = ((DropDownGroupTableViewCell*)_selectedCell).text;
            if(text.length <= 0)
                return 0;
            NSIndexPath *indexPath = [_gtable indexPathOfCell:_selectedCell];
            FieldDescript *expandInfo = [constraint valueAtKeyArrayIndex:indexPath.section valueArrayIndex:indexPath.row];
            
            BOOL hidden = NO;
            if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:hiddenPickerPlaceholderInFieldDescript:)])
            {
                hidden = [_delegate dynamicColumnFieldCore:self hiddenPickerPlaceholderInFieldDescript:expandInfo];
            }
            
            hidden = !hidden;
             
            NSInteger i = -1;
            if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:pickerDefaultRowInFieldDescript:)])
                i = [_delegate dynamicColumnFieldCore:self pickerDefaultRowInFieldDescript:expandInfo];
            if(i >= 0)
                return i + hidden;
            if([expandInfo.optionals containsObject:text] == YES)
                return [expandInfo.optionals indexOfObject:((DropDownGroupTableViewCell*)_selectedCell).text] + hidden;
            return 0;
            break;
        }
    }
    return 0;
}

- (NSInteger)numberOfRowInPickerPanelView:(XUIPickerPanelView *)ppvcl
{
    switch(ppvcl.vclType)
    {
        case DicPickPanelViewControllerTag:
        {
            __block NSArray *i = [NSArray new];
            [_newSingleSelect enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
             {
                 if ([ppvcl.toolBarTitle rangeOfString:key].location != NSNotFound)
                 {
                     i = obj;
                 }
             }];
            return i.count + 1;
            break;
        }
        case OtherPickPanelViewControllerTag:
        {
            XMSQueueDictionary *constraint = [_dataSource constraintOfDynamicColumnFieldCore:self];
            NSIndexPath *indexPath = [_gtable indexPathOfCell:_selectedCell];
            FieldDescript *expandInfo = [constraint valueAtKeyArrayIndex:indexPath.section valueArrayIndex:indexPath.row];
            
            BOOL hidden = NO;
            if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:hiddenPickerPlaceholderInFieldDescript:)])
            {
                hidden = [_delegate dynamicColumnFieldCore:self hiddenPickerPlaceholderInFieldDescript:expandInfo];
            }
            
            hidden = !hidden;
            
            if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:pickerNumberOfRowInFieldDescript:)])
            {
                NSInteger i = [_delegate dynamicColumnFieldCore:self pickerNumberOfRowInFieldDescript:expandInfo];
                if(i >= 0)
                    return i + hidden;
            }
            return expandInfo.optionals.count + hidden;
            break;
        }
    }
    return 0;
}

- (NSString *)pickerPanelView:(XUIPickerPanelView *)ppvcl titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    XMSQueueDictionary *constraint = [_dataSource constraintOfDynamicColumnFieldCore:self];
    NSIndexPath *indexPath = [_gtable indexPathOfCell:_selectedCell];
    FieldDescript *expandInfo = [constraint valueAtKeyArrayIndex:indexPath.section valueArrayIndex:indexPath.row];
    
    BOOL hidden = NO;

    if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:hiddenPickerPlaceholderInFieldDescript:)])
    {
        hidden = [_delegate dynamicColumnFieldCore:self hiddenPickerPlaceholderInFieldDescript:expandInfo];
    }
    
    if(hidden == NO)
    {
        if(row == 0)
        {
            NSString *placeholder = @"请选择";
            if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:pickerPlaceholder:inFieldDescript:)])
            {
                NSString *p = [_delegate dynamicColumnFieldCore:self pickerPlaceholder:placeholder inFieldDescript:expandInfo];
                return p;
            }
            return placeholder;
        }
        else
        {
            row -= 1;
        }
    }
    switch(ppvcl.vclType)
    {
        case DicPickPanelViewControllerTag:
        {
            __block SingleSelectInfo *i = [SingleSelectInfo new];
            [_newSingleSelect enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
             {
                 if ([ppvcl.toolBarTitle rangeOfString:key].location != NSNotFound)
                 {
                     i = obj[row];
                 }
             }];
            return i.value;
            break;
        }
        case OtherPickPanelViewControllerTag:
        {
            if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:pickerTitleForRow:inFieldDescript:)])
            {
                NSString *title = [_delegate dynamicColumnFieldCore:self pickerTitleForRow:row inFieldDescript:expandInfo];
                if(title != nil)
                    return title;
            }
            return expandInfo.optionals[row];
            break;
        }
    }
    return @"";
}

- (void)pickerPanelView:(XUIPickerPanelView *)ppvcl selectedRowAtIndex:(NSInteger)nIndex
{
    switch(ppvcl.vclType)
    {
        case DicPickPanelViewControllerTag:
        {
            DicDropDownGroupTableViewCell *cell = (DicDropDownGroupTableViewCell*)_selectedCell;
            if(nIndex == 0)
            {
                cell.dicData = nil;
                cell.text = @"";
            }
            else
            {
                [_newSingleSelect enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
                 {
                     if ([ppvcl.toolBarTitle rangeOfString:key].location != NSNotFound)
                     {
                         cell.dicData = obj[nIndex - 1];
                         cell.text = cell.dicData.value;
                     }
                 }];
            }
            break;
        }
        case OtherPickPanelViewControllerTag:
        {
            XMSQueueDictionary *constraint = [_dataSource constraintOfDynamicColumnFieldCore:self];
            NSIndexPath *indexPath = [_gtable indexPathOfCell:_selectedCell];
            FieldDescript *expandInfo = [constraint valueAtKeyArrayIndex:indexPath.section valueArrayIndex:indexPath.row];
            
            BOOL hidden = NO;
            if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:hiddenPickerPlaceholderInFieldDescript:)])
            {
                hidden = [_delegate dynamicColumnFieldCore:self hiddenPickerPlaceholderInFieldDescript:expandInfo];
            }
            
            NSString *ori = ((DropDownGroupTableViewCell*)_selectedCell).text;
            
            if(nIndex == 0 && hidden == NO)
            {
                ((DropDownGroupTableViewCell*)_selectedCell).text = @"";
            }
            else
            {
                hidden = !hidden;
                
                NSString *title = nil;
                if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:pickerSelectedTitleAtIndex:inFieldDescript:)])
                    title = [_delegate dynamicColumnFieldCore:self pickerSelectedTitleAtIndex:nIndex - hidden inFieldDescript:expandInfo];
                
                if(title != nil)
                    ((DropDownGroupTableViewCell*)_selectedCell).text = title;
                else
                    ((DropDownGroupTableViewCell*)_selectedCell).text = expandInfo.optionals[nIndex - hidden];
                
                if([_selectedCell isMemberOfClass:[DropDownTextGroupTableViewCell class]])
                {
                    ((DropDownTextGroupTableViewCell*)_selectedCell).selectText = ((DropDownGroupTableViewCell*)_selectedCell).text;
                }
            }
            
            NSString *newTitle = ((DropDownGroupTableViewCell*)_selectedCell).text;
            if([ori isEqualToString:newTitle] == NO)
            {
                if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:pickerDidChangeSelectedTitle:toNewTitle:inFieldDescript:)])
                    [_delegate dynamicColumnFieldCore:self pickerDidChangeSelectedTitle:ori toNewTitle:newTitle inFieldDescript:expandInfo];
            }
            
            break;
        }
    }
    _selectedCell = nil;
}

- (NSDate *)currentDateInPickerPanelView:(XUIPickerPanelView *)ppvcl
{
    switch (ppvcl.vclType)
    {
        case DatePickPanelViewControllerTag:
        {
            NSString *s = ((DateGroupTableViewCell*)_selectedCell).text;
            
            if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:datePickerDefaultDate:fieldDescript:)])
            {
                XMSQueueDictionary *constraint = [_dataSource constraintOfDynamicColumnFieldCore:self];
                __block FieldDescript *fileDescript = nil;
                [constraint enumerateArrayValueUsingBlock:^(id key, id value, NSUInteger idx, BOOL *stop)
                {
                    if([((FieldDescript*)value).fieldName isEqualToString:_selectedCell.szTag])
                    {
                        *stop = YES;
                        fileDescript = value;
                    }
                }];
                
                NSDate *now = [NSDate date];
                NSString *dateString = [now toStringDate:NSDateFormatByyMd];
                if(s.length > 0)
                    dateString = s;
                
                NSDate *tmp = [_delegate dynamicColumnFieldCore:self datePickerDefaultDate:dateString fieldDescript:fileDescript];
                if(tmp == nil)
                {
                    if([dateString toNSDate:NSDateFormatByyMd] != nil)
                        return [dateString toNSDate:NSDateFormatByyMd];
                    
                    return now;
                }
                else
                {
                    return tmp;
                }
            }
            else
            {
                if(s.length > 0)
                    return [s toNSDate:NSDateFormatByyMd];
                return [NSDate date];
            }
            
            break;
        }
        case DateTimePickPanelViewControllerTag:
        {
            NSString *s = ((DateTimeGroupTableViewCell*)_selectedCell).text;
            if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:datePickerDefaultDate:fieldDescript:)])
            {
                XMSQueueDictionary *constraint = [_dataSource constraintOfDynamicColumnFieldCore:self];
                __block FieldDescript *fileDescript = nil;
                [constraint enumerateArrayValueUsingBlock:^(id key, id value, NSUInteger idx, BOOL *stop)
                {
                    if([((FieldDescript*)value).fieldName isEqualToString:_selectedCell.szTag])
                    {
                        *stop = YES;
                        fileDescript = value;
                    }
                }];
                
                NSDate *now = [NSDate date];
                NSString *dateString = [now toStringDate:NSDateFormatByyMdHms];
                if(s.length > 0)
                    dateString = s;
                
                NSDate *tmp = [_delegate dynamicColumnFieldCore:self datePickerDefaultDate:dateString fieldDescript:fileDescript];
                if(tmp == nil)
                {
                    if([dateString toNSDate:NSDateFormatByyMdHms] != nil)
                        return [dateString toNSDate:NSDateFormatByyMdHms];
                    
                    return now;
                }
                else
                {
                    return tmp;
                }
            }
            else
            {
                if(s.length > 0)
                    return [s toNSDate:NSDateFormatByyMdHms];
                return [NSDate date];
            }
            break;
        }
        default:
            break;
    }
    return [NSDate date];
}

- (void)pickerPanelView:(XUIPickerPanelView *)ppvcl selectedDate:(NSDate *)date
{
    switch(ppvcl.vclType)
    {
        case DatePickPanelViewControllerTag:
        {
            NSString *format = NSDateFormatByyMd;
            if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:dateTimeFormatInFieldDescript:)])
            {
                XMSQueueDictionary *constraint = [_dataSource constraintOfDynamicColumnFieldCore:self];
                __block FieldDescript *fileDescript = nil;
                [constraint enumerateArrayValueUsingBlock:^(id key, id value, NSUInteger idx, BOOL *stop)
                {
                    if([((FieldDescript*)value).fieldName isEqualToString:_selectedCell.szTag])
                    {
                        *stop = YES;
                        fileDescript = value;
                    }
                }];
                NSString *f = [_delegate dynamicColumnFieldCore:self dateTimeFormatInFieldDescript:fileDescript];
                format = f.length > 0 ? f : format;
            }
            ((DateGroupTableViewCell*)_selectedCell).text = [date toStringDate:format];
            break;
        }
        case DateTimePickPanelViewControllerTag:
        {
            NSString *format = NSDateFormatByyMdHm;
            if([_delegate respondsToSelector:@selector(dynamicColumnFieldCore:dateTimeFormatInFieldDescript:)])
            {
                XMSQueueDictionary *constraint = [_dataSource constraintOfDynamicColumnFieldCore:self];
                __block FieldDescript *fileDescript = nil;
                [constraint enumerateArrayValueUsingBlock:^(id key, id value, NSUInteger idx, BOOL *stop)
                {
                    if([((FieldDescript*)value).fieldName isEqualToString:_selectedCell.szTag])
                    {
                        *stop = YES;
                        fileDescript = value;
                    }
                }];
                NSString *f = [_delegate dynamicColumnFieldCore:self dateTimeFormatInFieldDescript:fileDescript];
                format = f.length > 0 ? f : format;
            }
            ((DateTimeGroupTableViewCell*)_selectedCell).text = [date toStringDate:format];
            break;
        }
    }
    _selectedCell = nil;
}

- (void)pickerPanelViewDidCancel:(XUIPickerPanelView *)ppvcl
{
    _selectedCell = nil;
}

#pragma mark --
#pragma mark -- simpleDownload delegate

-(void)simpleDownloadManager:(XMSSimpleDownloadManager *)sdm finishedDownload:(CSimpleDownloadTaskTag *)tag
{
    UIImage *image = [UIImage imageWithContentsOfFile:tag.filePath];
    DispatchMainThreadAsync(^
    {
        if([tag.attachment isMemberOfClass:[ImagePanelStaticGroupTableViewCell class]])
        {
            [((ImagePanelStaticGroupTableViewCell*)tag.attachment) replaceImage:image atTag:[tag.filePath lastPathComponent]];
        }
        else if([tag.attachment isMemberOfClass:[ImagePanelGroupTableViewCell class]])
        {
            [((ImagePanelGroupTableViewCell*)tag.attachment) replaceImage:image atTag:[tag.filePath lastPathComponent]];
        }
        else if([tag.attachment isMemberOfClass:[MixedPanelGroupTableViewCell class]])
        {
            if([[tag.filePath pathExtension] isEqualToString:@"wav"] == YES)
            {
                //TODO
            }
            else if([[tag.filePath pathExtension] isEqualToString:@"mov"] == YES)
            {
                //TODO
            }
            else
            {
                [((MixedPanelGroupTableViewCell*)tag.attachment) replaceImage:image atTag:tag.filePath];
            }
        }
        else if([tag.attachment isMemberOfClass:[MixedPanelStaticGroupTableViewCell class]])
        {
            if([[tag.filePath pathExtension] isEqualToString:@"wav"] == YES)
            {
                //TODO
            }
            else if([[tag.filePath pathExtension] isEqualToString:@"mov"] == YES)
            {
                //TODO
            }
            else
            {
                [((MixedPanelStaticGroupTableViewCell*)tag.attachment) replaceImage:image atTag:tag.filePath];
            }
        }
    });
}

@end
